package task;

/**
 * 任务管理器，暂时用来更新排行榜
 */

import org.apache.commons.lang.time.DateUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Timer;

@WebListener()
public class TaskManager implements ServletContextListener {

    /**
     * 定时器
     */
    private Timer timer;
    /**
     * 无延迟
     */
    public static final long NO_DELAY = 0;

    // Public constructor is required by servlet spec
    public TaskManager() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------

    /**
     * 在Web应用启动时初始化任务
     */
    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
        //定义定时器
        timer = new Timer("排行榜更新", true);
        //启动备份任务,每月(4个星期)执行一次
        timer.schedule(new RankingTask(), NO_DELAY, DateUtils.MILLIS_PER_MINUTE);//每分钟任务
        //  timer.schedule(new BackUpTableTask(),NO_DELAY, 30000);
        System.out.println("初始化定时任务！");
    }

    /**
     * 在Web应用结束时停止任务
     */
    public void contextDestroyed(ServletContextEvent event) {
        timer.cancel(); // 定时器销毁
    }


}
